﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Fine.CRM.Common
{
    internal static class StringExtensions
    {
        /// <summary>
        /// Removes articles from a string to normalize it for sorting etc.
        /// </summary>
        public static string RemoveArticles(this string value, string replacement = "")
        {
            string patternTemplate = @"\b({0})\b";
            const System.Text.RegularExpressions.RegexOptions options = System.Text.RegularExpressions.RegexOptions.IgnoreCase;

            string[] articles = new[] { "the", "a", "an" };

            
            IEnumerable<System.Text.RegularExpressions.Regex> articleMatcher = articles.
                Select(x => new System.Text.RegularExpressions.Regex(string.Format(patternTemplate,x),options));

            string output = articleMatcher.
                Aggregate(value, (current, matcher) => matcher.Replace(current, replacement));
            
            
            return output;

        }

        public static string RemovePunctuation(this string value, string replacement="")
        {
            const string patternTemplate = @"[\p{P}\p{S}]";
            return Regex.Replace(value, patternTemplate, replacement);
        }

        /// <summary>
        /// Normalizes all consecutive white space into a single space and replace any non-space
        /// whitespace characters with a space.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string NormalizeWhiteSpace(this string value)
        {
             return System.Text.RegularExpressions.Regex.Replace(value, @"\s+", " ").Trim();
        }


        /// <summary>
        /// Converts the string into an array of words ordered in ascending order.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string[] ConvertToOrderedArray(this string value)
        {
            string[] temp = value.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
            return temp.OrderBy(word => word).ToArray<string>();
        }

        /// <summary>
        /// Generate an MD5 Hash of the string value.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string CreateMD5Hash(this string value)
        {
            string hash;
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                hash = BitConverter.ToString(
                  md5.ComputeHash(Encoding.UTF8.GetBytes(value))
                ).Replace("-", String.Empty);
            }
            return hash;
        }
    }
}
